<template>
  <div class="parent">
    <div class="child">
      <el-form :model="form" label-width="auto" style="max-width: 600px">
        <el-form-item label="用户名">
          <el-input v-model="form.userName" />
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="form.password" show-password />
        </el-form-item>
        <el-form-item label="验证码">
          <div class="captcha-container">
            <canvas ref="captchaCanvas" @click="refreshCaptcha"></canvas>
            <el-input v-model="userInput" placeholder="请输入验证码" />
            <!-- <el-button @click="verifyCaptcha">验证</el-button> -->
            <!-- <el-message :type="errorType" v-if="errorMessage">{{ errorMessage }}</el-message> -->
          </div>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">登录</el-button>
        
          <!-- <el-button>Cancel</el-button> -->
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios';
import { useRouter } from 'vue-router';
import { useCounterStore } from '@/stores/counter';

const store = useCounterStore();
const router = useRouter();

// 引用画布元素
const captchaCanvas = ref<HTMLCanvasElement | null>(null);
// 用户输入的验证码
const userInput = ref('');
// 错误信息
const errorMessage = ref('');
// 错误类型
const errorType = ref('error');
// 当前生成的验证码
const currentCaptcha = ref('');
// 验证码是否验证通过
const isCaptchaVerified = ref(false);


//#region  登录

// 定义响应数据类型
interface LoginResponse {
  code: number;
  msg: string;
  data: {
    nickName: string;
    userId: number;
    userName: string;
  };
}

const form = reactive({
  userName: '',
  password: '',
})

// 验证码字符集
const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
// 验证码长度
const captchaLength = 4;

// 生成随机验证码字符串
const generateCaptchaText = (): string => {
  let captcha = '';
  for (let i = 0; i < captchaLength; i++) {
    const randomIndex = Math.floor(Math.random() * characters.length);
    captcha += characters.charAt(randomIndex);
  }
  return captcha;
};

// 绘制验证码到画布
const drawCaptcha = (text: string) => {
  if (captchaCanvas.value) {
    const canvas = captchaCanvas.value;
    const ctx = canvas.getContext('2d');
    if (ctx) {
      // 设置画布大小
      canvas.width = 120;
      canvas.height = 40;
      // 清空画布
      ctx.clearRect(0, 0, canvas.width, canvas.height);
      // 设置字体样式
      ctx.font = '24px Arial';
      ctx.fillStyle = '#AB04E8';
      // 绘制验证码字符
      for (let i = 0; i < text.length; i++) {
        const x = 20 + i * 20;
        const y = 30;
        ctx.fillText(text[i], x, y);
      }
      // 添加干扰线
      for (let i = 0; i < 9; i++) {
        ctx.beginPath();
        ctx.moveTo(Math.random() * canvas.width, Math.random() * canvas.height);
        ctx.lineTo(Math.random() * canvas.width, Math.random() * canvas.height);
        ctx.strokeStyle = '#E0E0E0';
        ctx.stroke();
      }
      // 添加噪点
      for (let i = 0; i < 10; i++) {
        const x = Math.random() * canvas.width;
        const y = Math.random() * canvas.height;
        ctx.fillRect(x, y, 2, 2);
      }
    }
  }
};

// 刷新验证码
const refreshCaptcha = () => {
  currentCaptcha.value = generateCaptchaText();
  drawCaptcha(currentCaptcha.value);
  errorMessage.value = '';
  userInput.value = '';
  isCaptchaVerified.value = false;
};
const onSubmit = () => {
   // 验证码验证
   if (form.userName === "") {
    ElMessage.error("用户名不能为空");
    return
  }
  if (form.password === "") {
    ElMessage.error("密码不能为空");
    return
  }
  if (userInput.value === "") {
    ElMessage.error("验证码不能为空");
    return
  }
  if(currentCaptcha.value != userInput.value){
    ElMessage.error("验证码不正确")
    return
  }
  axios.get("https://localhost:7174/api/Message/Login", {
    params: {
      userName: form.userName,
      password: form.password
    }
  }).then(res => {
    if (res.data.code == 202) {
      ElMessage.success(res.data.msg)
      store.ccstore.nickName = res.data.data.nickName
      store.ccstore.userId = res.data.data.userId
      store.ccstore.userName = res.data.data.userName
      store.ccstore.depId = res.data.data.depId
      store.ccstore.levelRoleId = res.data.data.levelRoleId
      router.push("/MianView")
      console.log(res.data.data.nickName)
    } else {
      ElMessage.error(res.data.msg)
    }
  })
}

// 初始化验证码
onMounted(() => {
  refreshCaptcha();
})
//#endregion

</script>

<style scoped>
.captcha {
  cursor: pointer;
}

.parent {
  display: flex;
  justify-content: center;
  /* 水平居中 */
  align-items: center;
  /* 垂直居中 */
  height: 100vh;
  /* 设置父元素高度为视口高度 */
}

.child {
  background-color: #f0f0f0;
  padding: 70px;
}
</style>